package com.gitee.wsl.doc.prosemirror.state.command.selection

import com.gitee.wsl.doc.prosemirror.state.Command
import com.gitee.wsl.doc.prosemirror.state.CommandDispatch
import com.gitee.wsl.doc.prosemirror.state.EditorState
import com.gitee.wsl.doc.prosemirror.state.selection.TextSelection

class SelectTextblockSide(val side: Int): Command {
    override fun exec(
        state: EditorState,
        dispatch: CommandDispatch?,
    ): Boolean {
        val sel = state.selection
        val pos = if (side < 0) sel._from else sel._to
        var depth = pos.depth

        // 向上遍历找到非内联的文本块节点
        while (pos.node(depth).isInline) {
            if (depth == 0) return false
            depth--
        }

        // 检查当前节点是否为文本块
        if (!pos.node(depth).isTextblock) return false

        // 设置选择范围
        if (dispatch != null) {
            val selectionPos = if (side < 0) pos.start(depth) else pos.end(depth)
            val tr = state.tr.setSelection(TextSelection.create(state.doc, selectionPos))
            dispatch(tr)
        }
        return true
    }

    companion object{
        val selectTextblockStart = SelectTextblockSide(-1)
        val selectTextblockEnd = SelectTextblockSide(1)
    }
}

/// Moves the cursor to the start of current text block.
val Command.Companion.selectTextblockStart
    get() = SelectTextblockSide.selectTextblockStart

/// Moves the cursor to the end of current text block.
val Command.Companion.selectTextblockEnd
    get() = SelectTextblockSide.selectTextblockEnd
